package wqh.controller.file;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import wqh.domain.GeoLocation;
import wqh.pojo.MapRet;
import wqh.service.GeoLocationService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by wqh on 2017/1/12.
 */
@Controller
@CrossOrigin(origins = "*")
@RequestMapping(value = "/picture/geo_location")
public class GeoLocationPicture {

    @Autowired
    private GeoLocationService geoLocationService;

    @ResponseBody
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public Object mapUpload(HttpServletRequest httpServletRequest,
                            @RequestParam(value = "file",required = true)MultipartFile file,
                            @RequestParam(value = "id",required = true) long id)
    {
        try{
            GeoLocation g = geoLocationService.findById(id);
            if(g == null)
            {
                return MapRet.SQL_SELECT_NONE();
            }
            String localPath = "\\WEB-INF\\upload\\map\\";
            String uploadPath = httpServletRequest.getServletContext().getRealPath("/") + localPath;
            if(g.getUrl() != null && g.getUrl().length() != 0 && !g.getUrl().equals("0"))
            {
                String serverPath = httpServletRequest.getServletContext().getRealPath("/") + g.getUrl();
                File serverFile = new File(serverPath);
                if(serverFile.isFile() && serverFile.exists())
                {
                    serverFile.delete();
                }
            }
            File uploadDir = new File(uploadPath);
            if(!uploadDir.exists())
            {
                uploadDir.mkdirs();
            }
            String fileName = file.getOriginalFilename();
            if(fileName != null)
            {
                byte[] bytes = file.getBytes();
                fileName = System.currentTimeMillis() + fileName;
                File serverFile = new File(uploadDir.getAbsolutePath() + File.separator + fileName);
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
                stream.write(bytes);
                stream.close();
                g.setUrl(localPath + serverFile.getName());
                geoLocationService.update(g);
            }

        }catch (Exception e){
            e.printStackTrace();
            return MapRet.FILE_UPLOAD_ERROR();
        }
        return MapRet.FILE_UPLOAD_SUCCESS();
    }

    @ResponseBody
    @RequestMapping(value = "/download",method = RequestMethod.GET)
    public ResponseEntity<byte[]> mapDownload(HttpServletRequest httpServletRequest, HttpServletResponse response ,@RequestParam(value = "id",required = true)long id) throws IOException
    {
        try {
            GeoLocation g = geoLocationService.findById(id);
            String localPath = null;
            if(g != null) localPath = g.getUrl();
            String serverPath = httpServletRequest.getServletContext().getRealPath("/") + localPath;
            File file = new File(serverPath);
            if(!file.exists()) file = new File(httpServletRequest.getServletContext().getRealPath("/") + "\\img\\error.jpg");
            HttpHeaders httpHeaders = new HttpHeaders();
            String fileName = file.getName();
//            httpHeaders.setContentDispositionFormData("attachment",java.net.URLEncoder.encode(fileName,"UTF-8"));
            httpHeaders.setContentType(MediaType.IMAGE_JPEG);
            response.setHeader("Accept-Ranges", "bytes");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),httpHeaders, HttpStatus.CREATED);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

}
